<template>
  <div class="chat-list">
    <!-- 搜索框 -->
    <div class="search-box">
      <el-input
        v-model="searchKeyword"
        placeholder="搜索用户"
        :prefix-icon="Search"
        clearable
      />
    </div>

    <!-- 聊天列表 -->
    <div class="chat-items">
      <div
        v-for="chat in filteredChatList"
        :key="chat._id"
        class="chat-item"
        :class="{ active: chat.imKey === currentChatImKey }"
        @click="handleSelect(chat)"
      >
        <el-avatar :size="40" :src="chat.avatar" @error="() => true">
          {{ chat.userName.charAt(0) }}
        </el-avatar>
        <div class="chat-info">
          <div class="chat-header">
            <div class="user-info">
              <span class="username">{{ chat.userName }}</span>
              <el-tag v-if="chat.online === 1" size="small" type="success" effect="plain"
                >在线</el-tag
              >
              <el-tag v-else size="small" type="info" effect="plain">离线</el-tag>
            </div>
            <span class="time">{{ formatTime(chat.lastMessage?.time) }}</span>
          </div>
          <div class="chat-content">
            <span class="last-message">{{ chat.lastMessage?.content || "" }}</span>
            <el-badge
              v-if="chat.unreadCount"
              :value="chat.unreadCount"
              class="unread-badge"
              type="danger"
            />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, getCurrentInstance, onUnmounted, watch } from "vue";
import { Search } from "@element-plus/icons-vue";
import { formatTime } from "@/utils/format";
import { useMessageStore } from "@/stores/message";
import { storeToRefs } from "pinia";
import socket from "@/utils/socket";

const messageStore = useMessageStore();
const { sortedChatList, currentChatImKey } = storeToRefs(messageStore);

const emit = defineEmits(["select-chat"]);
const searchKeyword = ref("");
const isSearching = ref(false);

// 过滤后的聊天列表
const filteredChatList = computed(() => {
  const keyword = searchKeyword.value.trim().toLowerCase();
  const myImKey = localStorage.getItem("serviceImKey");
  if (!keyword) {
    isSearching.value = false;
    return sortedChatList.value.map((item) => {
      const uid = item.user === myImKey ? item.toUser : item.user;
      item.online = onlineStatus.value.find((onlineItem) => {
        return onlineItem.uid === uid;
      })?.online;
      return item;
    });
  }

  isSearching.value = true;
  const searchList = sortedChatList.value.filter((chat) =>
    chat.userName.toLowerCase().includes(keyword)
  );
  return searchList.map((item) => {
    item.online = onlineStatus.value.find((item) => {
      const uid = item.user;
      return item.user === uid || item.toUser === uid;
    })?.online;
    return item;
  });
});

const handleSelect = (chat) => {
  emit("select-chat", {
    id: chat._id,
    userName: chat.userName,
    avatar: chat.avatar,
    imKey: chat.imKey,
    userType: chat.userType,
    online: chat.online,
    uid: chat.uid,
  });
};

// 清空搜索
const handleClearSearch = () => {
  searchKeyword.value = "";
  isSearching.value = false;
};

// 定时刷新在线状态
const onlineStatus = ref([]);
const reloadOnlineStatus = async () => {
  const userIds = filteredChatList.value.map((item) => {
    const serviceInfo = localStorage.getItem("imUserInfo");
    const serviceUid = JSON.parse(serviceInfo)._id;
    return item.user !== serviceUid ? item.user : item.toUser;
  });
  socket.emit("userOnline", userIds, (res) => {
    if (res.code === 200) {
      onlineStatus.value = res.data || [];
      const instance = getCurrentInstance();
      instance?.proxy?.$forceUpdate();
    }
  });
};

const timer = ref(null);
timer.value = setInterval(() => {
  reloadOnlineStatus();
}, 10000);

onUnmounted(() => {
  if (timer.value) {
    clearInterval(timer.value);
    timer.value = null;
  }
});
</script>

<style scoped>
.chat-list {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.search-box {
  padding: 16px;
  border-bottom: 1px solid #e6e6e6;
}

.chat-items {
  flex: 1;
  overflow-y: auto;
}

.chat-item {
  padding: 12px 16px;
  display: flex;
  align-items: flex-start;
  cursor: pointer;
  transition: all 0.3s ease;
  border-left: 3px solid transparent;
}

.chat-item:hover {
  background-color: #f5f7fa;
}

.chat-item.active {
  background-color: #ecf5ff;
  border-left-color: #409eff;
}

.chat-info {
  flex: 1;
  margin-left: 12px;
  overflow: hidden;
}

.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 4px;
}

.username {
  font-weight: 500;
  color: #333;
}

.active .username {
  color: #409eff;
}

.time {
  font-size: 12px;
  color: #999;
}

.chat-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.last-message {
  flex: 1;
  font-size: 13px;
  color: #666;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.unread-badge {
  margin-left: 8px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.user-info .el-tag {
  margin-left: 4px;
  height: 20px;
  padding: 0 6px;
}
</style>
